package com.dy.springcloud.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//使用 @Component 直接为gateway注入一个GlobalFilter
//@Component
//GlobalFilter接口是gateway全局过滤器，Ordered指定过滤器执行顺序
public class CustomGatewayFilter implements GlobalFilter , Ordered {
    //过滤器方法
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //此gateway项目没有引入 web starter,不能用 HTTP Servlet Request 获取参数
        //获取参数
        //exchange.getRequest().getQueryParams().get() 返回一个参数的值的集合
        String pwd = exchange.getRequest().getQueryParams().getFirst("pwd");

        if(!"123".equals(pwd)) {
            //拒绝
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        //放行
        return chain.filter(exchange);
    }

    //返回数字越小，优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
